﻿using System;

namespace Microsoft.Popfly.GameCreator.GameEngine.Behaviors
{
    public class DistancedReverseOnceBehavior : IBehavior
    {
        private Game m_game;
        private BehaviorOwner m_owner;
        private MotionBehavior m_behavior;
        private double m_reverseAfterDistance;

        public DistancedReverseOnceBehavior(Game game, BehaviorOwner owner, MotionBehavior behavior, double reverseAfterDistance)
        {
            m_game = game;
            m_owner = owner;
            m_behavior = behavior;
            m_reverseAfterDistance = reverseAfterDistance;

        }

        #region Behavior Members

        public void Invoke(BehaviorOwner sender, Microsoft.Popfly.GameCreator.GameEngine.Events.PGCEventArgs args)
        {
            // This one will keep doing the behavior every frame
            Events.EventListener removeAfterInterval =
                m_owner.AddBehavior(
                    new Events.StandardListener(
                        m_game,
                        m_owner,
                        null,
                        m_behavior,
                        null,
                        null,
                        new Events.EveryFrameChecker(m_game)
                        )
                    );

            // This one will reverse it
            Events.IEventChecker eventChecker = new Events.DistanceEventChecker(m_game, m_owner, m_behavior, m_reverseAfterDistance, true);
            m_owner.AddBehavior(
                new Events.StandardListener(
                    m_game,
                    m_owner,
                    null,
                    new ReverseThenKillBehavior(m_owner, m_behavior, removeAfterInterval, eventChecker),
                    null,
                    null,
                    eventChecker
                    )
                );
        }

        #endregion
    }
}
